# @breif: 处理iptables -nvL [INPUT/OUTPUT] --line-numbers 的输出，
#         并存入dict便于和前端通信，显示
# @auther: Deminus 
# @Date: 2022/5/19



sample_result = \
[
'Chain OUTPUT (policy ACCEPT 1292 packets, 2683K bytes)', 
'num   pkts bytes target     prot opt in     out     source               destination         ', 
'1        0     0 ACCEPT     udp  --  *      *       172.26.240.0/20      0.0.0.0/0            udp spt:8080', 
'2        0     0 ACCEPT     tcp  --  *      *       172.26.240.0/20      0.0.0.0/0            tcp spt:8080 dpt:8081', 
'3        0     0 REJECT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable', 
'4       20  1960 ACCEPT     icmp --  *      *       0.0.0.0/0            172.26.240.0/20     ', 
'5       12  1176 REJECT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable'
]


# iptablesReuslt -> 命令的结果.splitlines();
# ruleList       -> 存放结果的list

def processChain(iptableResults):

  ruleList = []
  rulekey=['num','pkts','bytes','target','prot','opt','in','out','source','destination']

  for i in range(2,len(iptableResults)):
    rule={'num':0,'pkts':0,'bytes':0,'target':0,'prot':0,'opt':0,'in':0,'out':0,'source':0,'destination':0}
    line:list[str] = iptableResults[i].split()

    for j in range(len(rulekey)):
      #print(len(rulekey),len(line))
      rule[rulekey[j]] = line[j]

    
    if(line[4] == 'tcp' or line[4] == 'udp'):
      #遍历后面的元素
      for j in range(10,len(line)):
        index_spt = line[j].find('spt:')
        if(index_spt != -1):   #如果有spt
          rule['spt'] = line[j][4:]
        
        index_dpt = line[j].find('dpt:')
        if(index_dpt != -1):   #如果有dpt
          rule['dpt'] = line[j][4:]

    ruleList.append(rule)
    
  # print ("列表 : ", ruleList)
  # print("列表1:",ruleList[0])

  return ruleList


